import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:encrypt/encrypt.dart' as encrypt;
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:family_app/src/common/constants.dart';
import 'package:family_app/src/features/secure_vault/models/vault_item_model.dart';

/// 私密信息管理服务提供者
final secureVaultServiceProvider = Provider<SecureVaultService>((ref) {
  final dio = Dio(BaseOptions(
    baseUrl: AppConstants.apiBaseUrl,
    connectTimeout: const Duration(seconds: 5),
    receiveTimeout: const Duration(seconds: 10),
  ));
  return SecureVaultService(dio);
});

/// 私密信息管理服务
class SecureVaultService {
  final Dio _dio;
  final _secureVaultBox = Hive.box(AppConstants.secureVaultBox);
  late final encrypt.Encrypter _encrypter;
  late final encrypt.IV _iv;

  SecureVaultService(this._dio) {
    _initEncryption();
  }

  /// 初始化加密
  void _initEncryption() {
    // 使用固定的加密密钥和IV（在实际应用中应该使用更安全的方式存储密钥）
    final key = encrypt.Key.fromUtf8(AppConstants.encryptionKey);
    _iv = encrypt.IV.fromLength(16); // 使用全零IV
    _encrypter = encrypt.Encrypter(encrypt.AES(key));
  }

  /// 加密数据
  String _encrypt(String plainText) {
    return _encrypter.encrypt(plainText, iv: _iv).base64;
  }

  /// 解密数据
  String _decrypt(String encryptedText) {
    try {
      return _encrypter.decrypt64(encryptedText, iv: _iv);
    } catch (e) {
      return encryptedText; // 如果解密失败，返回原文
    }
  }

  /// 获取所有私密信息项
  Future<List<VaultItemModel>> getVaultItems() async {
    try {
      // 从本地存储获取私密信息项列表
      final encryptedData = _secureVaultBox.get('vault_items');
      if (encryptedData != null) {
        final decryptedData = _decrypt(encryptedData);
        final jsonData = json.decode(decryptedData) as List;
        return jsonData
            .map((item) =>
                VaultItemModel.fromJson(Map<String, dynamic>.from(item)))
            .toList();
      }

      // 模拟数据
      final items = _generateMockVaultItems();
      await _saveVaultItems(items);
      return items;
    } catch (e) {
      return [];
    }
  }

  /// 获取指定类型的私密信息项
  Future<List<VaultItemModel>> getVaultItemsByType(VaultItemType type) async {
    try {
      final items = await getVaultItems();
      return items.where((item) => item.type == type).toList();
    } catch (e) {
      return [];
    }
  }

  /// 获取收藏的私密信息项
  Future<List<VaultItemModel>> getFavoriteVaultItems() async {
    try {
      final items = await getVaultItems();
      return items.where((item) => item.isFavorite).toList();
    } catch (e) {
      return [];
    }
  }

  /// 搜索私密信息项
  Future<List<VaultItemModel>> searchVaultItems(String query) async {
    try {
      final items = await getVaultItems();
      final lowerQuery = query.toLowerCase();
      return items.where((item) {
        return item.title.toLowerCase().contains(lowerQuery) ||
            item.username.toLowerCase().contains(lowerQuery) ||
            (item.url?.toLowerCase().contains(lowerQuery) ?? false) ||
            (item.notes?.toLowerCase().contains(lowerQuery) ?? false);
      }).toList();
    } catch (e) {
      return [];
    }
  }

  /// 添加私密信息项
  Future<VaultItemModel?> addVaultItem({
    required String title,
    required VaultItemType type,
    required String username,
    required String password,
    String? url,
    String? notes,
    String? icon,
    bool isFavorite = false,
  }) async {
    try {
      // 创建新的私密信息项
      final item = VaultItemModel.create(
        title: title,
        type: type,
        username: username,
        password: password,
        url: url,
        notes: notes,
        icon: icon ?? WebsiteIcons.getIconByUrl(url),
        isFavorite: isFavorite,
      );

      // 保存到本地存储
      final items = await getVaultItems();
      items.add(item);
      await _saveVaultItems(items);

      return item;
    } catch (e) {
      return null;
    }
  }

  /// 更新私密信息项
  Future<VaultItemModel?> updateVaultItem({
    required String id,
    String? title,
    VaultItemType? type,
    String? username,
    String? password,
    String? url,
    String? notes,
    String? icon,
    bool? isFavorite,
  }) async {
    try {
      // 获取所有私密信息项
      final items = await getVaultItems();
      final index = items.indexWhere((item) => item.id == id);
      if (index == -1) return null;

      // 更新私密信息项
      final updatedItem = items[index].copyWith(
        title: title,
        type: type,
        username: username,
        password: password,
        url: url,
        notes: notes,
        icon: icon,
        isFavorite: isFavorite,
      );

      items[index] = updatedItem;
      await _saveVaultItems(items);

      return updatedItem;
    } catch (e) {
      return null;
    }
  }

  /// 删除私密信息项
  Future<bool> deleteVaultItem(String id) async {
    try {
      // 获取所有私密信息项
      final items = await getVaultItems();
      final index = items.indexWhere((item) => item.id == id);
      if (index == -1) return false;

      // 删除私密信息项
      items.removeAt(index);
      await _saveVaultItems(items);

      return true;
    } catch (e) {
      return false;
    }
  }

  /// 切换收藏状态
  Future<VaultItemModel?> toggleFavorite(String id) async {
    try {
      // 获取所有私密信息项
      final items = await getVaultItems();
      final index = items.indexWhere((item) => item.id == id);
      if (index == -1) return null;

      // 切换收藏状态
      final item = items[index];
      final updatedItem = item.copyWith(isFavorite: !item.isFavorite);

      items[index] = updatedItem;
      await _saveVaultItems(items);

      return updatedItem;
    } catch (e) {
      return null;
    }
  }

  /// 保存私密信息项列表到本地存储
  Future<void> _saveVaultItems(List<VaultItemModel> items) async {
    final jsonData = items.map((item) => item.toJson()).toList();
    final jsonString = json.encode(jsonData);
    final encryptedData = _encrypt(jsonString);
    await _secureVaultBox.put('vault_items', encryptedData);
  }

  /// 生成模拟私密信息项数据
  List<VaultItemModel> _generateMockVaultItems() {
    final now = DateTime.now();
    return [
      VaultItemModel(
        id: '1',
        title: 'Google',
        type: VaultItemType.website,
        username: 'user@example.com',
        password: 'Password123',
        url: 'https://google.com',
        notes: 'Google账号',
        icon: 'google',
        createdAt: now.subtract(const Duration(days: 30)),
        updatedAt: now.subtract(const Duration(days: 2)),
        isFavorite: true,
      ),
      VaultItemModel(
        id: '2',
        title: 'GitHub',
        type: VaultItemType.website,
        username: 'developer',
        password: 'SecurePassword!',
        url: 'https://github.com',
        notes: '代码仓库账号',
        icon: 'github',
        createdAt: now.subtract(const Duration(days: 60)),
        updatedAt: now.subtract(const Duration(days: 5)),
        isFavorite: false,
      ),
      VaultItemModel(
        id: '3',
        title: '微信',
        type: VaultItemType.app,
        username: 'wxid_123456',
        password: 'WeChatPwd789',
        notes: '微信账号',
        icon: 'wechat',
        createdAt: now.subtract(const Duration(days: 90)),
        updatedAt: now.subtract(const Duration(days: 10)),
        isFavorite: true,
      ),
      VaultItemModel(
        id: '4',
        title: '中国银行',
        type: VaultItemType.bankCard,
        username: '6222 **** **** 1234',
        password: '123456',
        notes: '储蓄卡',
        icon: 'bank',
        createdAt: now.subtract(const Duration(days: 120)),
        updatedAt: now.subtract(const Duration(days: 15)),
        isFavorite: false,
      ),
    ];
  }
}
